package com.lmaye.eshop.inventory.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import java.time.LocalDateTime;

/**
 * <p> 自定义填充公共 name 字段 </p>
 *
 * @author lmay.Zhou
 * @since 2019年3月12日 02:47:01
 */
public class MyMetaObjectHandler implements MetaObjectHandler {

    @SuppressWarnings("Duplicates")
    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();

        //设置创建时间
        Object createDate = getFieldValByName("createDate", metaObject);
        if (createDate == null) {
            setFieldValByName("createDate", now, metaObject);
        }

        //设置修改时间
        Object lastModifiedAt = getFieldValByName("lastModifiedAt", metaObject);
        if (lastModifiedAt == null) {
            setFieldValByName("lastModifiedAt", now, metaObject);
        }

        //设置版本号
        Object version = getFieldValByName("version", metaObject);
        if (version == null) {
            setFieldValByName("version", 1, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //设置修改时间
        Object lastModifiedAt = getFieldValByName("lastModifiedAt", metaObject);
        if (lastModifiedAt == null) {
            setFieldValByName("lastModifiedAt", LocalDateTime.now(), metaObject);
        }
    }
}
